package com.whfc.openapi.interceptor;

import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.WebUtils;
import com.whfc.hdc.dto.HdcAccessTokenDTO;
import com.whfc.openapi.api.sys.service.OpenApiTokenService;
import com.whfc.openapi.constant.OpenApiConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021/12/22 18:03
 */
@Component
public class OpenApiHdcAuthInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OpenApiTokenService openApiTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证accessToken
        String accessToken = request.getParameter("accessToken");
        String requestUri = request.getRequestURI();
        logger.info("preHandle,uri:{},host:{},accessToken:{}", requestUri, WebUtils.getClientIp(request), accessToken);
        if (StringUtils.isEmpty(accessToken)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "缺少accessToken参数");
        }
        HdcAccessTokenDTO accessTokenDTO = openApiTokenService.validateHdcOpenApiToken(accessToken);
        request.setAttribute(OpenApiConst.OPENAPI_HDC_CLIENT, accessTokenDTO);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
